package Controller;

import Service.SupervisorService;
import Service.RandomDelivery;
import Service.RandomProductDelivery;
import Entity.Orders;
import Entity.Products;
import Entity.Robot;
import View.Warehouse;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.List;

public class SupervisorController extends JFrame {
    private final SupervisorService supervisorService;

    private JTextArea logTextArea;
    private JTextArea messageTextArea;
    private JList<Robot> robotListUI;
    private DefaultListModel<Robot> robotListModel;

    private JButton deactivateButton;
    private JButton reactivateButton;

    private JSpinner orderFrequencySpinner;
    private JSpinner productFrequencySpinner;

    private Timer robotUpdateTimer;
    private Timer orderArrivalTimer;
    private Timer productArrivalTimer;
    private Warehouse warehouseView;
    public SupervisorController(SupervisorService supervisorService) {
        this.supervisorService = supervisorService;
        warehouseView = new Warehouse(this.supervisorService.getAllRobots());
        initGUI();
        startRobotUpdateTimer();
        startOrderArrivalTimer();
        startProductArrivalTimer();
    }

    private void initGUI() {
        setTitle("Supervisor Controller");
        setSize(1200, 800);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new BorderLayout());

        // 左侧面板：机器人状态和控制
        JPanel leftPanel = new JPanel(new BorderLayout());
        leftPanel.setBorder(BorderFactory.createTitledBorder("Robot Status"));

        // 机器人列表
        robotListModel = new DefaultListModel<>();

        robotListUI = new JList<>(robotListModel);
        robotListUI.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        updateRobotList();
        JScrollPane robotScrollPane = new JScrollPane(robotListUI);
        robotScrollPane.setPreferredSize(new Dimension(300, 600));
        leftPanel.add(robotScrollPane, BorderLayout.CENTER);

        // 按钮面板
        JPanel buttonsPanel = new JPanel(new GridLayout(2, 1, 5, 5));
        deactivateButton = new JButton("Deactivate Robot");
        reactivateButton = new JButton("Reactivate Robot");
        buttonsPanel.add(deactivateButton);
        buttonsPanel.add(reactivateButton);
        leftPanel.add(buttonsPanel, BorderLayout.SOUTH);

        add(leftPanel, BorderLayout.WEST);

        // 中央面板：日志和消息
        JPanel centerPanel = new JPanel(new GridLayout(2, 1));

        // 日志面板
        JPanel logPanel = new JPanel(new BorderLayout());
        logPanel.setBorder(BorderFactory.createTitledBorder("Robots Activity Logs"));
        logTextArea = new JTextArea();
        logTextArea.setEditable(false);
        JScrollPane logScrollPane = new JScrollPane(logTextArea);
        logPanel.add(logScrollPane, BorderLayout.CENTER);
        centerPanel.add(logPanel);

        // 消息面板
        JPanel messagePanel = new JPanel(new BorderLayout());
        messagePanel.setBorder(BorderFactory.createTitledBorder("Messages from Supply and Customer Orders"));
        messageTextArea = new JTextArea();
        messageTextArea.setEditable(false);
        JScrollPane messageScrollPane = new JScrollPane(messageTextArea);
        messagePanel.add(messageScrollPane, BorderLayout.CENTER);
        centerPanel.add(messagePanel);

        add(centerPanel, BorderLayout.CENTER);

        // 右侧面板：模拟控制
        JPanel rightPanel = new JPanel(new GridLayout(2, 1));
        rightPanel.setBorder(BorderFactory.createTitledBorder("Simulation Controls"));

        // 订单到达频率
        JPanel orderPanel = new JPanel();
        orderPanel.add(new JLabel("Order Arrival Frequency (ms):"));
        orderFrequencySpinner = new JSpinner(new SpinnerNumberModel(7000, 100, 20000, 100));
        orderPanel.add(orderFrequencySpinner);
        rightPanel.add(orderPanel);

        // 产品到达频率
        JPanel productPanel = new JPanel();
        productPanel.add(new JLabel("Product Arrival Frequency (ms):"));
        productFrequencySpinner = new JSpinner(new SpinnerNumberModel(7000, 100, 20000, 100));
        productPanel.add(productFrequencySpinner);
        rightPanel.add(productPanel);

        add(rightPanel, BorderLayout.EAST);

        // 底部面板：应用频率按钮
        JPanel bottomPanel = new JPanel();
        JButton applyFrequencyButton = new JButton("Apply Frequencies");
        bottomPanel.add(applyFrequencyButton);
        add(bottomPanel, BorderLayout.SOUTH);

        // 按钮事件绑定
        deactivateButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                Robot selectedRobot = robotListUI.getSelectedValue();
                if (selectedRobot != null) {
                    supervisorService.deactivateRobot(selectedRobot.getId());
                    addLog("Robot " + selectedRobot.getId() + " deactivated.");
                    updateRobotList();
                } else {
                    JOptionPane.showMessageDialog(null, "Please select a robot to deactivate.");
                }
            }
        });

        reactivateButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                Robot selectedRobot = robotListUI.getSelectedValue();
                if (selectedRobot != null) {
                    supervisorService.reactivateRobot(selectedRobot.getId());
                    addLog("Robot " + selectedRobot.getId() + " reactivated.");
                    updateRobotList();
                } else {
                    JOptionPane.showMessageDialog(null, "Please select a robot to reactivate.");
                }
            }
        });

        applyFrequencyButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int orderFreq = (int) orderFrequencySpinner.getValue();
                int productFreq = (int) productFrequencySpinner.getValue();
                // 重新启动订单和产品到达定时器
                restartOrderArrivalTimer(orderFreq);
                restartProductArrivalTimer(productFreq);
                addLog("Order arrival frequency set to " + orderFreq + " ms.");
                addLog("Product arrival frequency set to " + productFreq + " ms.");
            }
        });

        setLocationRelativeTo(null);
    }

    // 更新机器人列表显示
    /*private void updateRobotList() {

        List<Robot> robots = supervisorService.getAllRobots();
        robotListModel.clear();
        for (Robot robot : robots) {
            robotListModel.addElement(robot);
        }
        warehouseView.repaint();
    }
*/private void updateRobotList() {
        // 记录当前选中的机器人
        Robot selectedRobot = robotListUI.getSelectedValue();

        // 获取最新的机器人列表
        List<Robot> robots = supervisorService.getAllRobots();

        // 清空并重新添加机器人数据
        robotListModel.clear();
        for (Robot robot : robots) {
            robotListModel.addElement(robot);
        }

        // 恢复选中的机器人
        if (selectedRobot != null) {
            int index = robotListModel.indexOf(selectedRobot);
            if (index != -1) {
                robotListUI.setSelectedIndex(index);
            }
        }

        // 重新绘制仓库视图
        warehouseView.repaint();
    }

    // 添加日志到日志文本区
    private void addLog(String log) {
        logTextArea.append(log + "\n");
    }

    // 添加消息到消息文本区
    private void addMessage(String message) {
        messageTextArea.append(message + "\n");
    }

    // 启动机器人更新定时器
    private void startRobotUpdateTimer() {
        robotUpdateTimer = new Timer(100, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                supervisorService.updateRobots();
                // 获取并显示日志和消息
                List<String> logs = supervisorService.getLogs();
                for (String log : logs) {
                    addLog(log);
                }
                logs.clear();

                List<String> messages = supervisorService.getMessages();
                for (String msg : messages) {
                    addMessage(msg);
                }
                messages.clear();

                updateRobotList();
            }
        });
        robotUpdateTimer.start();
    }

    // 启动订单到达定时器
    private void startOrderArrivalTimer() {
        int initialDelay = (int) orderFrequencySpinner.getValue();
        orderArrivalTimer = new Timer(initialDelay, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                Orders order = RandomDelivery.generateOrder();
                supervisorService.handleNewOrder(order);
                addLog("Generated new order: " + order.getName());
            }
        });
        orderArrivalTimer.start();
    }

    // 启动产品到达定时器
    private void startProductArrivalTimer() {
        int initialDelay = (int) productFrequencySpinner.getValue();
        productArrivalTimer = new Timer(initialDelay, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                Products product = RandomProductDelivery.generateProduct();
                supervisorService.handleNewProduct(product);
                addLog("Generated new product: " + product.getName());
            }
        });
        productArrivalTimer.start();
    }

    // 重新启动订单到达定时器
    private void restartOrderArrivalTimer(int newDelay) {
        orderArrivalTimer.stop();
        orderArrivalTimer = new Timer(newDelay, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                Orders order = RandomDelivery.generateOrder();
                supervisorService.handleNewOrder(order);
                addLog("Generated new order: " + order.getName());
            }
        });
        orderArrivalTimer.start();
    }

    // 重新启动产品到达定时器
    private void restartProductArrivalTimer(int newDelay) {
        productArrivalTimer.stop();
        productArrivalTimer = new Timer(newDelay, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                Products product = RandomProductDelivery.generateProduct();
                supervisorService.handleNewProduct(product);
                addLog("Generated new product: " + product.getName());
            }
        });
        productArrivalTimer.start();
    }
}
